有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java实体数组到JavaScript数组

我想把名为“entities”的全局属性放在JS范围中Entity基本上是描述Person的Java类

public class EntityJS extends ScriptableObject {
    private String firstName;
    private String lastName;
    private Double salary;
    private String email;

    @Override
    public String getClassName() {
        return "Entity";
    }

    public EntityJS() {
    }

    public EntityJS(String firstName, String lastName, Double salary, String email) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.salary = salary;
        this.email = email;
    }

    public void jsConstructor() {
        this.firstName = "";
        this.lastName = "";
        this.salary = 0.;
        this.email = "";
    }

    public void jsSet_salary(Double value) {
        this.salary = value;
    }

    public Double jsGet_salary() {
        return this.salary;
    }

    public void jsSet_firstName(String value) {
        this.firstName = value;
    }
    //the rest of getters & setters
}

Entity类几乎与EntityJS类相同,只是它只扩展了javaObject

我想允许javascript用户修改全局变量“entities”。在执行用户脚本之后,我想将该对象检索回Java(并在稍后执行一些操作)

我已经用结果和预期返回值对有趣的行进行了注释。 以下是我尝试执行用户代码的代码:

public String execute(String code, ObservableList<Entity> entities) {
    Context context = Context.enter();
    try {
        Scriptable scope = context.initStandardObjects();

        ScriptableObject.defineClass(scope, EntityJS.class, true, true);

        EntityJS[] objects = new EntityJS[entities.size()];
        for(int i = 0; i < entities.size(); ++i){
            objects[i] = new EntityJS(entities.get(i).getFirstName(), entities.get(i).getLastName(), entities.get(i).getSalary(), entities.get(i).getEmail());
        }

        ScriptableObject.putProperty(scope, "e1", Context.javaToJS(objects, scope));
        // typing "e1" (which is equal to "code" value) returns "[Lentity.EntityJS;@7959b389"

        Object[] array = entities.toArray();
        ScriptableObject.putProperty(scope, "e2", array);
        // same for e1

        Object wrappedOut = Context.javaToJS(entities, scope);
        ScriptableObject.putProperty(scope, "e3", wrappedOut);
        //this works quite nice, but it doesn't behave like JS object
        //it returns, good-looking array:
        //[Entity{firstName='Alwafaa', lastName='Abacki', salary=1000.0, email='zdzisiek@adad.com'},
        //Entity{firstName='chero', lastName='Cabacki', salary=2000.0, email='bfadaw@dadaad.com'}]
        //Unfortunately, if I want to get e.g. salary value I have to call
        //e.get(0).getSalary() which returns string :(
        //if I want to add number I have to call
        //Number(e.get(0).getSalary()) to get Number

        ScriptableObject.putProperty(scope, "e4", Context.javaToJS(objects[0], scope));
        //this results in "TypeError: Cannot find default value for object."

        Object result = context.evaluateString(scope, code, "<cmd>", 1, null);
        return context.toString(result);
    } catch (Exception ex) {
        System.out.println(ex.getMessage());
        return ex.getMessage();
    } finally {
        Context.exit();
    }
}

我想给用户提供类似JS的“实体”数组,可以这样修改:

    entities.forEach(function(entity){entity.salary += 1000;})

当然,我希望salary属性是Number。 有人知道我该怎么做吗? 提前谢谢


共 (2) 个答案

  1. # 1 楼答案

    您可以在服务器端将Java对象转换为JSON字符串,并将其传递给客户端javascript。当客户机收到来自服务器的响应(包含项目的JSON字符串)时,您可以解析JSON

    您可以将Java对象转换为JSON(在服务器端),请参阅以下教程:

    GSONhttps://www.mkyong.com/java/how-do-convert-java-object-to-from-json-format-gson-api/

    杰克逊https://www.mkyong.com/java/jackson-2-convert-java-object-to-from-json/

    这是如何在js中解析JSON对象。 https://www.w3schools.com/js/js_json_parse.asp

    I want to allow javascript user modify global variable "entities". After executing user's script, I want to retrieve this object back to Java (and perform some operations later on).

    您可以向服务器发出AJAX请求,以传递修改过的对象。同样,在js端,将这些对象转换为JSON,然后将它们传递给服务器,并将JSON字符串解析为对象的集合(数组)

    这是如何将javascript对象转换为JSON字符串 Convert JS object to JSON string

    I have Java Application, which uses Rhino (as in tags). I have TextArea, where user types JS code. I need to give user the entities object.

    因此,将用户输入的文本传递到您的服务器,并对其进行解析。但请确保您传递的是有效的JSON

  2. # 2 楼答案

    根据您的JS版本,您可以执行以下操作:

    ES5

    function Person(firstName, lastName, salary, email) {
            this.firstName = firstName;
            this.lastName = lastName;
            this.salary = salary;
            this.email = email;
        }
    
    var john = new Person("john", "smith", 500, "john.smith@john.com");
    var jane = new Person("jane", "doe", 650, "jane.doe@jane.net");
    var people = [john, jane];
    
    //mutating the original values
    people.forEach(function(person) {person.salary += 500})
    

    ES6

    class Person {
      constructor(firstName, lastName, salary, email) {
        this.firstName = firstName;
            this.lastName = lastName;
            this.salary = salary;
            this.email = email;
      }
    }
    
    let john = new Person("john", "smith", 500, "john.smith@john.com");
    let jane = new Person("jane", "doe", 650, "jane.doe@jane.net");
    let people = [john, jane];
    
    people.forEach(person => person.salary += 500);